import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 62536
 * Date: 2024-03-02
 * Time: 10:29
 */
public class Node {
    int val;
    Node next;
    Node random;

    public Node(int val) {
        this.val = val;
        this.next = null;
        this.random = null; //随机节点可能为空，也可能指向包括自己在内的任一节点
    }


    //随机链表的复制
    public Node copyRandomList(Node head) {

        //用Map来创造一个一样值的链表
        HashMap<Node,Node> map = new HashMap<>();
        Node cur = head;
        while(cur != null) {
            Node newNode = new Node(cur.val);
            map.put(cur,newNode);

            cur = cur.next;
        }

        //用map。get()方法来复制之前的映射关系
        cur = head;
        while(cur != null) {
            map.get(cur).next = map.get(cur.next);
            map.get(cur).random = map.get(cur.random);

            cur = cur.next;
        }


        return map.get(head);
    }
}
